package source

import (
	"../api"
	"fmt"
	"bytes"
	"strings"
	"time"
	"github.com/PuerkitoBio/goquery"
)

var (
	yzsCats = []category{
		category{
			url: "http://videos.yizhansou.com",
			cat: "meiju",
			fn:  analyseMeiJu,
		},
		category{
			url: "http://v.yizhansou.com/tvb",
			cat: "tvb",
			fn:  nil,
		},
		category{
			url: "http://v.yizhansou.com/ndj",
			cat: "ndj",
			fn:  nil,
		},
		category{
			url: "http://v.yizhansou.com/rhj",
			cat: "rhj",
			fn:  nil,
		},
		category{
			url: "http://v.yizhansou.com/mv",
			cat: "mv",
			fn:  nil,
		},
	}
)

func request(cat category) {
	buf, err := client.Get(cat.url)
	if err != nil {
		fmt.Println("加载内容失败", err)
		return
	}
	cat.fn(cat, buf)
}

func analyseMeiJu(cat category, buf []byte) {
	doc, err := goquery.NewDocumentFromReader(bytes.NewReader(buf))
	if err != nil {
		fmt.Println("解析页面失败")
	}
	doc.Find("body>table:nth-child(10)").Find("tr:not(:first-child)").Each(func(i int, selection *goquery.Selection) {
		sel := selection.Find("td")
		if sel.Length() == 4 {
			var href, aka, name, season, updateNum, update string
			for i := 0; i < 4; i++ {
				if i < 3 {
					asel := sel.Eq(i).Find("a")
					text := asel.Text()
					if i == 0 {
						tHref, ok := asel.Attr("href")
						if !ok {
							fmt.Println("不存在链接属性")
							return
						}
						href = cat.base + tHref
						arr := strings.Split(text, " - ")
						aka, name = strings.TrimSpace(arr[0]), strings.TrimSpace(arr[1])
					} else if i == 1 {
						season = text
					} else if i == 2 {
						updateNum = text
					}
				} else {
					update = sel.Eq(i).Text()
				}
			}
			timeLayout := "2006-01-02"
			loc, err := time.LoadLocation("Local")
			if err != nil {
				fmt.Println("获取时区失败", err)
				return
			}
			tm, err := time.ParseInLocation(timeLayout, update, loc)
			if err != nil {
				fmt.Println("解析时间异常", err)
				return
			}
			it := item{
				Cat:       cat.cat,
				Name:      name,
				Aka:       aka,
				Season:    season,
				Href:      href,
				UpdateNum: updateNum,
				Updated:   tm,
			}
			mr, err := api.NewDouBan().Search(it.Name, 0, 20)
			if err != nil {
				fmt.Println("查询豆瓣异常", err)
				return
			}
			fmt.Printf("%+v\n", it)
			for _, m := range mr.Movies {
				fmt.Printf("%+v\n", m)
			}
			fmt.Println("#################################################")
		}
	})
	fmt.Println("###############################################")
	nextBtn := doc.Find("li.next>a")
	if nextBtn.Length() == 1 {
		h, ok := nextBtn.Attr("href")
		if ok {
			c := category{
				base: cat.base,
				url:  cat.base + h,
				cat:  cat.cat,
				fn:   cat.fn,
			}
			time.Sleep(5 * time.Second)
			fmt.Println(c.url)
			request(c)
		}
	}
}

func start() {
	for _, c := range yzsCats {
		if c.fn != nil {
			c.base = c.url
			request(c)
		}
	}
}

func NewYzsSource() {
	start()
}
